//
//  AsyncTask.m
//  SVW_STAR
//
//  Created by fanty on 13-5-28.
//  Copyright (c) 2013年 fanty. All rights reserved.
//

#import "AsyncTask.h"
#import "ASIHTTPRequest.h"
#import "ThreadTask.h"
#import "CheckOperatorDelegate.h"
#import "BaseCheckOperator.h"

@interface AsyncTask()

@property(nonatomic,strong) ThreadTask* threadTask;

-(void)finish;
@end

@implementation AsyncTask
@synthesize request;

-(id)init{
    self=[super init];
    if(self){
        self.checkOperator=[[BaseCheckOperator alloc] init];
        
    }
    return self;
}

-(void)dealloc{
    self.threadTask=nil;
    self.checkOperator=nil;
    self.request=nil;
    self.parser=nil;
}

-(void)cancel{
    self.finishBlock=nil;
    [self.threadTask cancel];
    [self.request setCompletionBlock:nil];
    [self.request setFailedBlock:nil];
    [self.request cancel];
}

-(void)finish{
#ifdef DEBUG
    NSLog(@"success xml:%@",[self.request responseString]);
#endif

    self.threadTask=[ThreadTask asyncStart:^{
        BOOL ret=YES;
        if(self.checkOperator!=nil)
            ret=[self.checkOperator checkResponseString:request];
        if(ret && self.parser!=nil)
            [self.parser parse:[self.request responseData]];
    } end:^{
        if(self.finishBlock!=nil){
            self.finishBlock();
        }
        [self cancel];
    }];
}

-(void)start{
    __block AsyncTask* selfObj=self;
    [self.request setCompletionBlock:^{
            [selfObj finish];
    }];
    
    [self.request setFailedBlock:^{
        [selfObj finish];
    }];
    
    [self.request start];
    
}

-(id)result{
    return [self.parser getResult];
}

-(int)statusCode{
    return [self.checkOperator statusCode];
}

-(NSString*)errorMessage{
    return [self.checkOperator errorMessage];

}

-(NSData*)responseData{
    return [self.request responseData];
}

@end



